<?php
/**
 * Created by PhpStorm.
 * User: liu
 * Date: 17-3-4
 * Time: 上午12:14
 */

namespace Cframe;

class Response {
    public $header = [];
    public $code = 200;
    public $data = null;
    public static $is_json = false;
    public $option = [];
    public function __construct($info,$code = 200,array $header = [],$option = []){
        if (is_null($info) || is_bool($info)){
            return false;
        }
        $this->data = $info;
        $this->code = $code;
        $this->headers($header);
        $this->option = $option;
        // return $this;
    }

    public function send(){
        $data = $this->data;
        http_response_code($this->code);
        foreach ($this->header as $key=>$val){
            header($key.":".$val);
        }
        echo self::check($data);

        if (function_exists('fastcgi_finish_request')) {
            // 提高页面响应
            fastcgi_finish_request();
        }
    }

    public function headers(array $header = []){
        $this->header = array_merge($this->header,$header);
        return $this;
    }

    public function contentType($type,$charset = 'UTF-8'){
        if (static::$is_json){
            $type = 'text/json';
        }
        $this->header['Content-Type'] = $type  . '; charset=' . $charset;
        return $this;
    }

    private static function check($var,$format = ''){
        if (is_array($var)){
            switch ($format){
                case "xml":
                    $data = self::run("xml",$var);
                    break;
                default:
                    $data = static::run("json",$var);
            }
        } else {
            $data = self::run("string",$var);
        }
        return $data;
    }

    public static function run($type = "string",$info){
        switch ($type){
            case "json":
                static::$is_json = true;
                if (is_array($info)) {
                    $info = json_encode($info);
                }
                break;
        }
        return $info;
    }
}